package server.utils;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

public class Log {
	/**
	 * Logfile's name.
	 */
	private String logFile;
	/**
	 * Configuration file's name.
	 */
	private String confLog;
	/**
	 * Constructor.
	 * @param logFile Logfile's name.
	 * @param confLog Configurationfile's name.
	 */
	public Log(String logFile, String confLog) {
		this.logFile = logFile;
		this.confLog = confLog;
	}
	/**
	 * Write into logfile only.
	 * @param msg Message to write into logfile.
	 */
	public synchronized void println(String msg) {
		this.write(msg, false, logFile);
	}
	/**
	 * Write into logfile and console if needed.
	 * @param msg Message to write into logfile.
	 * @param b True - writes to console and file. 
	 * 			False - writes to file.
	 */
	public synchronized void println(String msg, boolean b) {
		this.write(msg, b, logFile);
	}
	/**
	 * Write into file and console.
	 * @param msg Message to write into file.
	 * @param b True - writes to console and file. 
	 * 			False - writes to file.
	 */
	private synchronized void write(String msg, boolean b, String logFile) {
		PrintWriter writer = null;
		try {
			writer = new PrintWriter(new FileWriter(logFile, true));
			writer.println(Utils.now() + " " + msg);
			if (b) System.out.println(Utils.now() + " " + msg);
		} catch (IOException e) {
			System.err.println(Utils.now() + " - Error writing logfile!");
		} finally {
			writer.close();
		}
	}
	/**
	 * Reads server configurations.
	 * @return ArrayList<String> with configurations, each on a seperate entry.
	 * 			NULL if error occurred.
	 */
	public ArrayList<String> readConf() {
		ArrayList<String> output = new ArrayList<String>();
		BufferedReader bfr = null;
		String line;
		try {
			bfr = new BufferedReader(new FileReader(confLog));
			while ((line = bfr.readLine()) != null) {
				output.add(line);
			}
		} catch (FileNotFoundException e) {
			this.println(Utils.now()+ " - Error reading configuration file!");
		} catch (IOException e) {
			this.println(Utils.now()+ " - Error reading " +
					"configuration file's line!");
		} finally {
			try {
				bfr.close();
			} catch (IOException e) {
				this.println(Utils.now() + " - Reader closing error!", true);
			}
		}
		return output;
		
	}
}
